package cn.hesion.leetcode;
/**
 * ClassName: FindFrequentTreeSum <br/>
 * Description: <br/>
 * date: 2022/6/15 7:36<br/>
 *
 * @author Hesion<br />
 * @version
 * @since JDK 1.8
 */

import java.util.*;

/**
 * @author: hesion
 * @create: 2022-06-15 07:36
 **/
public class FindFrequentTreeSum {
    Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();

    public int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int sum = root.val;
        sum += dfs(root.left);
        sum += dfs(root.right);
        cnt.put(sum, cnt.getOrDefault(sum, 0) + 1);
        return sum;
    }

    public int[] findFrequentTreeSum(TreeNode root) {
        List<int[]> ans = new ArrayList<int[]>();
        List<Integer> ret = new ArrayList<Integer>();
        dfs(root);
        for (Integer key : cnt.keySet()) {
            int[] tmp = new int[2];
            tmp[0] = cnt.get(key);
            tmp[1] = key;
            ans.add(tmp);
        }
        ans.sort((a,b)->{
            return b[0]-a[0];
        });

        ret.add(ans.get(0)[1]);
        for (int i = 1; i < ans.size(); ++i) {
            if (ans.get(i)[0] == ans.get(i - 1)[0])
                ret.add(ans.get(i)[1]);
            else break;
        }

        return ret.stream().mapToInt(Integer::valueOf).toArray();
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(2);
        root.right = new TreeNode(-5);
        int[] frequentTreeSum = new FindFrequentTreeSum().findFrequentTreeSum(root);
        System.out.println(Arrays.toString(frequentTreeSum));
    }
}
